// 全局工具函数
class MirrorTransferSystem {
    constructor() {
        this.currentTaskId = null;
        this.pollingInterval = null;
        this.init();
    }

    init() {
        this.bindEvents();
        this.checkDockerStatus();
        console.log('Mirror Transfer System initialized');
    }

    bindEvents() {
        document.addEventListener('click', (e) => {
            console.log('点击事件:', e.target);
            
            // 删除服务器按钮
            if (e.target.closest('.delete-server-btn')) {
                const button = e.target.closest('.delete-server-btn');
                const serverId = button.dataset.serverId;
                console.log('删除服务器:', serverId);
                this.deleteServer(serverId);
                return;
            }

            // 测试连接按钮
            if (e.target.closest('.test-server-btn')) {
                const button = e.target.closest('.test-server-btn');
                const serverId = button.dataset.serverId;
                console.log('测试服务器:', serverId);
                this.testConnection(serverId);
                return;
            }

            // 表单提交事件
            if (e.target.closest('form')) {
                const form = e.target.closest('form');
                if (form.id === 'addServerForm') {
                    e.preventDefault();
                    console.log('提交服务器表单');
                    this.handleServerFormSubmit(form);
                }
            }
        });
        
        // 认证方式切换
        const authRadios = document.querySelectorAll('input[name="auth_type"]');
        authRadios.forEach(radio => {
            radio.addEventListener('change', (e) => {
                this.toggleAuthType(e.target.value);
            });
        });
    }

    async handleServerFormSubmit(form) {
        const submitBtn = form.querySelector('button[type="submit"]');
        const originalText = submitBtn.innerHTML;

        try {
            submitBtn.disabled = true;
            submitBtn.innerHTML = '<span class="loading-spinner"></span> 添加中...';

            const formData = new FormData(form);
            const requestData = {};
            for (let [key, value] of formData.entries()) {
                requestData[key] = value;
            }

            console.log('提交表单数据:', requestData);

            const response = await fetch(form.action, {
                method: form.method,
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: new URLSearchParams(requestData).toString()
            });

            if (!response.ok) {
                const errorText = await response.text();
                throw new Error(`HTTP错误! 状态: ${response.status}, 响应: ${errorText}`);
            }

            const data = await response.json();
            console.log('表单提交响应:', data);
            
            if (data.error) {
                throw new Error(data.error);
            }

            this.showToast(data.message || '服务器添加成功', 'success');
            
            // 关闭模态框并刷新页面
            const modal = bootstrap.Modal.getInstance(document.getElementById('addServerModal'));
            if (modal) {
                modal.hide();
            }
            
            setTimeout(() => {
                window.location.reload();
            }, 1000);

        } catch (error) {
            console.error('Server form submission error:', error);
            this.showToast(error.message, 'error');
        } finally {
            submitBtn.disabled = false;
            submitBtn.innerHTML = originalText;
        }
    }

    // 删除服务器方法
    async deleteServer(serverId) {
        if (!confirm('确定要删除这个服务器配置吗？此操作不可恢复。')) {
            return;
        }

        const button = document.querySelector(`.delete-server-btn[data-server-id="${serverId}"]`);
        if (!button) {
            console.error('删除按钮未找到');
            return;
        }

        const originalText = button.innerHTML;

        try {
            button.disabled = true;
            button.innerHTML = '<span class="loading-spinner"></span>';

            console.log('发送删除请求:', serverId);
            const response = await fetch(`/api/servers/${serverId}`, {
                method: 'DELETE',
                headers: {
                    'Content-Type': 'application/json',
                }
            });

            const data = await response.json();
            console.log('删除响应:', data);

            if (response.ok) {
                this.showToast(data.message || '服务器删除成功', 'success');
                // 移除对应的表格行
                const row = document.querySelector(`tr[data-server-id="${serverId}"]`);
                if (row) {
                    row.style.opacity = '0.5';
                    setTimeout(() => row.remove(), 500);
                } else {
                    // 如果找不到行，刷新页面
                    setTimeout(() => window.location.reload(), 1000);
                }
            } else {
                throw new Error(data.error || '删除失败');
            }

        } catch (error) {
            console.error('Delete server error:', error);
            this.showToast(error.message, 'error');
        } finally {
            button.disabled = false;
            button.innerHTML = originalText;
        }
    }

    // 测试服务器连接
    async testConnection(serverId) {
        const button = document.querySelector(`.test-server-btn[data-server-id="${serverId}"]`);
        if (!button) {
            console.error('找不到测试按钮，服务器ID:', serverId);
            this.showToast('找不到测试按钮', 'error');
            return;
        }

        const originalText = button.innerHTML;
        const originalClass = button.className;

        try {
            // 更新按钮状态
            button.disabled = true;
            button.className = originalClass + ' disabled';
            button.innerHTML = '<span class="loading-spinner"></span> 测试中...';

            console.log('开始测试服务器连接，ID:', serverId);

            // 发送测试请求
            const response = await fetch(`/api/servers/${serverId}/test`);
            console.log('测试响应状态:', response.status);

            if (!response.ok) {
                const errorText = await response.text();
                throw new Error(`HTTP错误: ${response.status}, ${errorText}`);
            }

            const data = await response.json();
            console.log('测试结果数据:', data);

            // 根据结果更新UI
            if (data.success) {
                this.showToast('✅ 连接测试成功！', 'success');
                button.innerHTML = '<i class="bi bi-check-circle-fill"></i> 成功';
                button.className = originalClass.replace('btn-primary', 'btn-success');
            } else {
                this.showToast(`❌ 连接测试失败: ${data.message}`, 'error');
                button.innerHTML = '<i class="bi bi-x-circle-fill"></i> 失败';
                button.className = originalClass.replace('btn-primary', 'btn-danger');
            }

        } catch (error) {
            console.error('测试连接发生错误:', error);
            this.showToast('⚠️ 测试连接时发生错误: ' + error.message, 'error');
            button.innerHTML = '<i class="bi bi-x-circle-fill"></i> 错误';
            button.className = originalClass.replace('btn-primary', 'btn-warning');
        } finally {
            // 3秒后恢复按钮状态
            setTimeout(() => {
                button.disabled = false;
                button.innerHTML = '<i class="bi bi-plug"></i> 测试';
                button.className = originalClass;
            }, 3000);
        }
    }

    // 切换认证方式显示
    toggleAuthType(authType) {
        const authSections = document.querySelectorAll('.auth-section');
        authSections.forEach(section => {
            section.style.display = 'none';
        });

        const targetSection = document.getElementById(`${authType}Auth`);
        if (targetSection) {
            targetSection.style.display = 'block';
        }
    }

    async monitorTaskProgress(taskId) {
        this.currentTaskId = taskId;
        const progressArea = document.getElementById('progressArea');
        const progressBar = document.getElementById('progressBar');
        const taskStatus = document.getElementById('taskStatus');
        const taskMessage = document.getElementById('taskMessage');
        const taskIdSpan = document.getElementById('taskId');
        const cancelBtn = document.getElementById('cancelBtn');

        // 显示进度区域
        if (progressArea) progressArea.style.display = 'block';
        if (taskIdSpan) taskIdSpan.textContent = taskId;

        // 显示取消按钮
        if (cancelBtn) {
            cancelBtn.style.display = 'block';
            cancelBtn.onclick = () => this.cancelTask(taskId);
        }

        // 开始轮询任务状态
        this.pollingInterval = setInterval(async () => {
            try {
                const response = await fetch(`/api/tasks/${taskId}`);
                const task = await response.json();

                // 更新UI
                if (progressBar) {
                    progressBar.style.width = `${task.progress}%`;
                    const progressText = progressBar.querySelector('.progress-text');
                    if (progressText) progressText.textContent = `${task.progress}%`;
                }
                
                if (taskStatus) {
                    taskStatus.textContent = this.getStatusText(task.status);
                    taskStatus.className = `badge ${this.getStatusClass(task.status)}`;
                }
                
                if (taskMessage) taskMessage.textContent = task.message || '';

                // 任务完成或失败时停止轮询
                if (['completed', 'failed', 'cancelled'].includes(task.status)) {
                    clearInterval(this.pollingInterval);
                    if (cancelBtn) cancelBtn.style.display = 'none';
                    
                    if (task.status === 'completed') {
                        this.showToast('任务完成！', 'success');
                    } else if (task.status === 'failed') {
                        this.showToast('任务失败', 'error');
                    }
                }

            } catch (error) {
                console.error('Error polling task status:', error);
            }
        }, 2000);
    }

    async cancelTask(taskId) {
        if (confirm('确定要取消这个任务吗？')) {
            try {
                const response = await fetch(`/api/tasks/${taskId}/cancel`, {
                    method: 'POST'
                });
                const data = await response.json();
                
                if (response.ok) {
                    this.showToast('任务已取消', 'warning');
                    if (this.pollingInterval) clearInterval(this.pollingInterval);
                    const cancelBtn = document.getElementById('cancelBtn');
                    if (cancelBtn) cancelBtn.style.display = 'none';
                } else {
                    throw new Error(data.error);
                }
            } catch (error) {
                this.showToast(error.message, 'error');
            }
        }
    }

    async checkDockerStatus() {
        const statusElement = document.getElementById('dockerStatus');
        if (!statusElement) return;

        try {
            const response = await fetch('/api/docker/status');
            const data = await response.json();
            
            statusElement.textContent = data.status === 'connected' ? '已连接' : '未连接';
            statusElement.className = `badge ${data.status === 'connected' ? 'bg-success' : 'bg-danger'}`;
            
        } catch (error) {
            console.error('Error checking Docker status:', error);
        }
    }

    getStatusText(status) {
        const statusMap = {
            'pending': '等待中',
            'pulling': '拉取镜像',
            'saving': '保存镜像',
            'transferring': '传输中',
            'completed': '完成',
            'failed': '失败',
            'cancelled': '已取消'
        };
        return statusMap[status] || status;
    }

    getStatusClass(status) {
        const classMap = {
            'pending': 'bg-secondary',
            'pulling': 'bg-info',
            'saving': 'bg-warning',
            'transferring': 'bg-primary',
            'completed': 'bg-success',
            'failed': 'bg-danger',
            'cancelled': 'bg-secondary'
        };
        return classMap[status] || 'bg-secondary';
    }

    showToast(message, type = 'info') {
        // 检查 SweetAlert2 是否可用
        if (typeof Swal === 'undefined') {
            // 备用方案：使用浏览器原生 alert
            alert(`${type.toUpperCase()}: ${message}`);
            return;
        }
        
        const Toast = Swal.mixin({
            toast: true,
            position: 'top-end',
            showConfirmButton: false,
            timer: 3000,
            timerProgressBar: true,
            didOpen: (toast) => {
                toast.addEventListener('mouseenter', Swal.stopTimer);
                toast.addEventListener('mouseleave', Swal.resumeTimer);
            }
        });

        Toast.fire({
            icon: type,
            title: message
        });
    }

    // 文件下载工具函数
    downloadFile(content, fileName, contentType = 'application/octet-stream') {
        const blob = new Blob([content], { type: contentType });
        const url = window.URL.createObjectURL(blob);
        const link = document.createElement('a');
        link.href = url;
        link.download = fileName;
        link.click();
        window.URL.revokeObjectURL(url);
    }

    // 格式化文件大小
    formatFileSize(bytes) {
        if (bytes === 0) return '0 B';
        const k = 1024;
        const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
        const i = Math.floor(Math.log(bytes) / Math.log(k));
        return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
    }

    // 格式化时间
    formatDateTime(dateString) {
        const date = new Date(dateString);
        return date.toLocaleString('zh-CN', {
            year: 'numeric',
            month: '2-digit',
            day: '2-digit',
            hour: '2-digit',
            minute: '2-digit',
            second: '2-digit'
        });
    }
}

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
    // 检查必要的全局变量
    if (typeof bootstrap === 'undefined') {
        console.error('Bootstrap 未加载');
    }
    
    if (typeof Swal === 'undefined') {
        console.warn('SweetAlert2 未加载，将使用备用提示');
    }
    
    window.mirrorTransferSystem = new MirrorTransferSystem();
    
    // 添加页面加载动画
    document.body.classList.add('fade-in');
    
    // 自动聚焦到第一个输入框
    const firstInput = document.querySelector('form input[type="text"], form input[type="email"], form input[type="password"]');
    if (firstInput) {
        setTimeout(() => firstInput.focus(), 300);
    }
    
    console.log('页面初始化完成');
});

// 调试快捷键
document.addEventListener('keydown', function(e) {
    // Ctrl+Shift+D 显示调试信息
    if (e.ctrlKey && e.shiftKey && e.key === 'D') {
        console.log('当前页面状态:', {
            servers: document.querySelectorAll('.test-server-btn').length + ' 个服务器',
            time: new Date().toLocaleString()
        });
    }
});

// 显示调试信息
function showDebugInfo(data) {
    let debugInfo = document.getElementById('debugInfo');
    let debugContent = document.getElementById('debugContent');
    
    if (!debugInfo) {
        debugInfo = document.createElement('div');
        debugInfo.id = 'debugInfo';
        debugInfo.style.cssText = 'display: none; position: fixed; bottom: 10px; right: 10px; width: 400px; max-height: 300px; overflow-y: auto; background: white; border: 1px solid #ccc; z-index: 1000; padding: 10px; border-radius: 5px; box-shadow: 0 4px 6px rgba(0,0,0,0.1);';
        
        debugContent = document.createElement('pre');
        debugContent.id = 'debugContent';
        debugContent.style.cssText = 'margin: 0; font-size: 12px; max-height: 250px; overflow-y: auto;';
        
        const closeBtn = document.createElement('button');
        closeBtn.textContent = '关闭';
        closeBtn.style.cssText = 'position: absolute; top: 5px; right: 5px; padding: 2px 5px; font-size: 12px;';
        closeBtn.onclick = () => debugInfo.style.display = 'none';
        
        debugInfo.appendChild(closeBtn);
        debugInfo.appendChild(debugContent);
        document.body.appendChild(debugInfo);
    }
    
    debugContent.textContent = JSON.stringify(data, null, 2);
    debugInfo.style.display = 'block';
    
    setTimeout(() => {
        debugInfo.style.display = 'none';
    }, 10000);
}
